import ajax from './ajax'
import store from '@/store'
import 'dingtalk-jsapi/entry/mobile';
import openLink from 'dingtalk-jsapi/api/biz/util/openLink';

// 封装的支付接口
export function corpPay(orderNo) {
	const systemInfo = dd.getSystemInfoSync();
	const { platform } = systemInfo
	const type = platform === "Android" ? "android" : "ios"
	if (!orderNo) return new Promise((resolve, reject) => {
		uni.showToast({
			title: '未传入订单号'
		})
		resolve()
	})
	return new Promise((resolve, reject) => {
			ajax({
				method: 'post',
				url: '/outing/mobile/pay/chargePay',
				header: 'application/x-www-form-urlencoded',
				data: {
					orderNo,
					type
				}
			}).then(res => {
				if (res.data && res.data.ios && res.data.body) {
					// ios端直接调用支付宝支付
					// 支付宝支付
					dd.pay({
						info: res.data.body, // 订单信息
						has_alipay: false, // 默认值false，true表示支付串中指定了支付账号，不需要走绑定支付宝流程
						success: res => {
							console.log('支付接口调用成功', res);
							resolve(res)
							if (res.resultStatus === '9000') {
								uni.redirectTo({
									url: `/subPages/personalCenter/recharge/success?orderNo=${orderNo}`
								})
							} else {
								const code = res.resultStatus;
								setTimeout(() => {
									uni.redirectTo({
										url: `/subPages/personalCenter/recharge/fail?orderNo=${orderNo}`
									})
								}, 1000);
								if (code === '4000') return uni.showToast({title: '订单支付失败！'});
								if (code === '6001') return uni.showToast({title: '订单支付取消！'});
								if (code === '6002') return uni.showToast({title: '网络链接出错！'});
								return uni.showToast({title: '支付出现错误'});
							}
							/*{
									memo: 'xxxx', // 保留参数，一般无内容
									result: 'xxxx', // 本次操作返回的结果数据
									resultStatus: '' // 本次操作的状态返回值，标识本次调用的结果
							}*/
						},
						fail: err => {
							console.log('支付失败', err);
							reject(err)
							uni.showToast({title: '支付失败'}, 2);
							uni.redirectTo({
								url: `/subPages/personalCenter/recharge/fail?orderNo=${orderNo}`
							})
						}
					});
				} else if (res.data && res.data.url) {
					store.commit('changeLinkOrderNo', orderNo)
					// 安卓端跳转H5页面进行支付
					openLink({
					    url: res.data.url
					})
					resolve(res)
				} else if(res.code !== 8200) {
					reject(res)
					uni.showToast({
						title: res.message
					})
				} else {
					reject(res)
					console.log('未知错误', res)
				}
			}).catch(err => {
				reject(err)
				uni.redirectTo({
					url: `/subPages/personalCenter/recharge/fail?orderNo=${orderNo}`
				})
			})
		})
	}
